package com.example.shop.user.controller;

import com.example.shop.common.api.ResponseResult;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.common.enums.SessionAttributeKey;
import com.example.shop.pojo.User;
import com.example.shop.user.dto.BrowsingHistory;
import com.example.shop.user.dto.BrowsingHistoryQueryParam;
import com.example.shop.user.service.BrowsingHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/user/browsingHistory")
public class BrowsingHistoryController {

    @Autowired
    BrowsingHistoryService browsingHistoryService;

    @PostMapping(value = "/browse",consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseResult<List<BrowsingHistory>> obtainBrowsingHistory(HttpSession session,@RequestBody @Validated @NotNull BrowsingHistoryQueryParam queryParam, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
        }
        User user = (User) session.getAttribute(SessionAttributeKey.NOW_LOGIN_USER.getKey());
        List<BrowsingHistory> list = browsingHistoryService.obtainBrowsingHistory(user,queryParam);
        return ResponseResult.auto(ServiceStateCode.SUCCESS,list);
    }

    @GetMapping(value = "/delete/{goodsId}",consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseResult<Boolean> deleteBrowsingHistory(HttpSession session,@RequestBody @PathVariable("goodsId") long goodsId){
        User user = (User) session.getAttribute(SessionAttributeKey.NOW_LOGIN_USER.getKey());
        boolean result = browsingHistoryService.deleteBrowsingHistory(user, goodsId);
        return ResponseResult.auto(ServiceStateCode.SUCCESS,result);
    }


}
